﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.IO;
using Microsoft;

namespace CSharp_homework4
{

    //订单管理控制台
    //订单类 
    [Serializable]                                       //可序列化的类，不能被继承
    public class Order                                                                      
    {
        //基本数据                                         ，感觉这些基本数据可以不用写，直接用属性拿取就好了？？？
        //private int id;                                   //订单编号
        //private string pName;                              //商品名字
        //private string cName;                                //客户名称
        //private List<OrderDetails> items;                     //订单明细
        //private double price = 0;                            //订单金额

        //订单基本属性
        public int orderId { get; set; }
        public string productName { get; set; }
        public string customerName { get; set; }
        public double orderPrice { get; }
        public List<OrderDetails> orderItems;

        //构造函数
        public Order() { }
        public Order(int id,/*string pName,*/string cName,List<OrderDetails> items)
        {
            orderId = id;
            //productName = pName;
            customerName = cName;
            orderItems = items;
            foreach(OrderDetails item in orderItems)
            {
                orderPrice += item.itemPrice;
            }
        }

        //重写Equals方法，确保添加的订单不重复
        public override bool Equals(object obj)
        {
            Order order = obj as Order;
            if (order != null && this.orderId == order.orderId) { return true; }
            return false;
        }

        public override int GetHashCode()
         {
            return base.GetHashCode();
         }

        //添加ToString方法，显示订单信息
        public override string ToString()
        {
            string outInform = "订单编号：" + orderId + "    " + "下单客户名字为：" + customerName + "    " + /*"商品名字：" + productName + */"    " + "商品金额：" + orderPrice + "\n"+"\n";
            foreach(OrderDetails items in orderItems)
            {
                outInform += items.ToString();
            }
            return outInform;
        }
    }

    //订单明细类
    [Serializable]
    public class OrderDetails
    {
        //基本数据
        private string id;                                     //条目编号
        private Product product;                               //商品
        private int num;                                       //商品数量
        //private double price;                                  //条目价格

        //订单基本属性
        public string itemId { get; }
        public Product itemProduct { get; set; }
        public int productNum { get; set; }
        public double itemPrice { get; }

        //构造函数
        public OrderDetails() { }
        public OrderDetails(string id,Product product,int num)
        {
            itemId = id;
            itemProduct = product;
            productNum = num;
            itemPrice = num * product.productPrice;
        }

        //重写Equals方法，确保添加的订单明细不重复
        public override bool Equals(object obj)
        {
            OrderDetails orderDetail = obj as OrderDetails;
            if (orderDetail != null && this.itemProduct == orderDetail.itemProduct) { return true; }                //不要重复添加相同商品
            return false;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        //添加ToString方法，显示订单明细信息
        public override string ToString()
        {
            return "明细：" + itemId + "    " + "商品名：" + itemProduct.productName + "    " + "商品数：" + productNum + "    " + "商品价格：" + itemPrice + "\n";
        }
    }

    //订单任务类
    public class OrderService
    {
        //基本数据
        private List<Order> order;
        //private bool isChange = false;
        //private bool isDelete = false;
        //订单数据保存在List中

        //属性
        public List<Order> orders { get; set; }  
                
        //构造函数
        public OrderService(List<Order> order)
        {
            orders = order;
        }

        //在订单删除、修改失败时能够产生异常并显示给客户错误信息
        /*public void ReturnWrong(Order o)
        {
            if (isChange == false)
            {
                Console.WriteLine("订单修改失败！");
            }
            if (isDelete == false)
            {
                Console.WriteLine("订单删除失败！");
            }
        }*/

        //提供排序方法对保存的订单进行排序：默认使用订单号排序；也可以使用Lambda表达式进行自定义排序
        public void RangeOrder()
        {
                orders.Sort((o1, o2) => o1.orderId - o2.orderId);                               //默认排序
        }

        public void RangeOrder1()
        {
            orders.Sort((o1, o2) => Convert.ToInt32(o1.orderPrice - o2.orderPrice));
        }

        //添加订单
        public void AddOrder(Order o)
        {
            if (orders.Contains(o)==false)
            {
                orders.Add(o);
                Console.WriteLine("订单添加成功！");
            }
            else
            {
                Console.WriteLine("已有订单，无法重复添加！");
            }
        }

        //删除订单，在订单删除失败时，显示错误信息
        public void DeleteOrder(Order o)
        {
            if (orders.Contains(o)==true)
            {
                orders.Remove(o);
                //isDelete = true;
            }
            else
            {
                Console.WriteLine("找不到该订单，删除失败！");
            }
        }

        //修改订单，在订单修改失败时，显示错误信息
        public void ChangeOrder(Order o,int id,string cName,List<OrderDetails> items)
        {
            if (o != null && o.orderId != id && o.customerName != cName && o.orderItems != items)
            {
                o.orderId = id;
                o.customerName = cName;
                o.orderItems = items;
                //isChange = true;
                Console.WriteLine("订单修改成功！");
            }
            else if (o.orderId == id) { Console.WriteLine("订单编号重复，无法修改！"); }
            else if (o.customerName == cName) { Console.WriteLine("客户名重复，无法修改！"); }
            else if (o.orderItems != items) { Console.WriteLine("订单项重复，无法修改！"); }
            else
            {
                Console.WriteLine("该订单不存在，修改失败！");
            }
        }

        //查询订单,使用LINQ实现各种查询功能，查询结果按订单金额排序返回
        public string CheckOrder(/*List<Order> orders,*/int option, string check)
        {
            string s = "";
            ///int option;
            //string check;
            //Console.WriteLine("查询订单：按订单编号（1），按客户名（2），按商品名（3），按订单金额（4）,显示所有订单（5）。");
            //option = int.Parse(Console.ReadLine());
            switch (option)
            {
                case 1:
                    //Console.WriteLine("请输入要查询的信息：");
                    //check = Console.ReadLine();
                    var query1 = from order1 in orders
                                where order1.orderId == int.Parse(check)
                                orderby order1.orderPrice
                                select order1;
                    foreach(var order1 in query1)
                    {
                        s = order1.ToString()+ s;
                    }
                        break;
                case 2:
                    //Console.WriteLine("请输入要查询的信息：");
                    //check = Console.ReadLine();
                    var query2 = from order2 in orders
                                where order2.customerName == check
                                orderby order2.orderPrice
                                select order2;
                    foreach (var order2 in query2)
                    {
                        s = order2.ToString() + s;
                    }
                    break;
                case 3:
                    //Console.WriteLine("请输入要查询的信息：");
                    //check = Console.ReadLine();
                    var query3 = from order3 in orders
                                where order3.productName == check
                                orderby order3.orderPrice
                                select order3;
                    foreach (var order3 in query3)
                    {
                        s = order3.ToString() + s;
                    }
                    break;
                case 4:
                    //Console.WriteLine("请输入要查询的信息：");
                    //check = Console.ReadLine();
                    var query4 = from order4 in orders
                                where order4.orderPrice == int.Parse(check)
                                orderby order4.orderPrice
                                select order4;
                    foreach (var order4 in query4)
                    {
                        s = order4.ToString() + s;
                    }
                    break;
                /*case 5:
                    var query5 = from order5 in orders
                                 orderby order5.orderPrice
                                 select order5;
                    foreach (var order5 in query5)
                    {
                        Console.WriteLine(order5.ToString());
                    }
                    break;*/
            }
            return s;
        }

        //将所有订单序列化为XML文件
        public void Export(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(List<Order>));          //初始化，将指定的对象反序列化
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                xs.Serialize(fs, orders);
                Console.WriteLine("序列化了！");
            }
        }

        //添加一个Import方法可以从XML文件中载入订单
        public void Import(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(List<Order>));
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    orders = (List<Order>)xs.Deserialize(fs);
                    Console.WriteLine("载入了！");
                }
            }
            catch (FileNotFoundException ex)
            {
                throw ex;
            }
        }

    }

    //客户类
    [Serializable]
    public class Customer
    {
        //基本数据
        private string name;                           //客户名               

        //客户基本属性
        public string customerName { get; }

        //构造函数
        public Customer(string name)
        {
            customerName = name;
        }

        //添加ToString方法，显示订单信息
        public override string ToString()
        {
            return customerName;
        }
    }

    //货物类
    [Serializable]
    public class Product
    {
        //基本数据
        private string id;                               //商品编号
        private string name;                             //商品名字
        private double price;                            //商品价格

        //货物基本属性
        public string productId { get;}
        public string productName { get; }
        public double productPrice { get; set; }

        //构造函数
        public Product() { }
        public Product(string id, string name, double price)
        {
            productId = id;
            productName = name;
            productPrice = price;
        }

        //添加ToString方法，显示订单信息
        public override string ToString()
        {
            return productId + "    " + productName + "    " + productPrice;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*//生成商品
            Product p1 = new Product("p00", "苹果", 12.1);
            Product p2 = new Product("p01", "香蕉", 7.9);
            Product p3 = new Product("p02", "梨子", 6.2);

            //生成客户
            Customer c1 = new Customer("张三");
            Customer c2 = new Customer("李四");

            //生成订单项
            OrderDetails i1 = new OrderDetails("i01", p1, 3);
            OrderDetails i2 = new OrderDetails("i02", p2, 2);
            OrderDetails i3 = new OrderDetails("i03", p3, 5);
            OrderDetails i4 = new OrderDetails("i04", p1, 6);

            //生成订单项列表
            List<OrderDetails> l1 = new List<OrderDetails>();
            List<OrderDetails> l2 = new List<OrderDetails>();
            List<OrderDetails> l3 = new List<OrderDetails>();

            //往其中加入订单项
            l1.Add(i1);
            l1.Add(i3);
            l2.Add(i2);
            l3.Add(i2);
            l3.Add(i3);

            //生成订单
            Order o1 = new Order(01, "张三", l1);
            Order o2 = new Order(02, "张三", l2);
            Order o3 = new Order(03, "李四", l3);

            //生成订单列表
            List<Order> orders = new List<Order>();

            //生成订单服务对象
            OrderService os = new OrderService(orders);

            //添加订单
            os.AddOrder(o1);
            //os.AddOrder(o1);  
            os.AddOrder(o2);
            os.AddOrder(o3);

            //删除订单
            //os.DeleteOrder(o1);
            //os.DeleteOrder(o1);

            //修改订单
            //os.ChangeOrder(o1, 01, "李四", l3);
            //os.ChangeOrder(o1, 04, "李四", l3);

            //查询订单
            //os.CheckOrder();

            //订单排序
            //os.RangeOrder();
            //foreach(Order o in os.orders)
            //{
                //Console.WriteLine(o);
            //}
            os.RangeOrder1();
            foreach (Order o in os.orders)
            {
                Console.WriteLine(o);
            }

            //Export,Import
            try
            {
                os.Export(".orders.xml");
                os.Import(".orders.xml");
            }
            catch (System.IO.FileNotFoundException)
            {
                Console.WriteLine("文件路径不存在！");
            }


            //随机生成0~1000之间的100个整数，使用Linq语句对这些数据从小到大排序，并求和与平均数
            //int[] array = new int[100];
            //Random ra = new Random();
            //double sum = 0;
            //double aver = 0;
            //for(int i = 0; i < 100; i++)
            //{
                //array[i] = ra.Next(1000) + 1;
            //}
            //var query = from n in array
                         //orderby n
                         //select n;
            //foreach (var n in query)
            //{
                //Console.WriteLine(n);
                //sum += n;
            //}
            //aver = sum / 100;
            //Console.WriteLine(sum);
            //Console.WriteLine(aver);
            //Console.WriteLine("!");*/
        }
    }
}
